local addon = LibStub("AceAddon-3.0"):GetAddon("Poppins")

local LibSharedMedia = LibStub("LibSharedMedia-3.0")

local count = 0
local weak = {__mode='k'}
local cache = setmetatable({}, weak)
local used = setmetatable({}, weak)

local prototype = addon:CreateClass("CheckButton", addon.Base)
addon.Popup = prototype

function prototype:Create()
	local popup = next(cache)
	if popup then
		cache[popup] = nil
	else
		count = count + 1
		local name = format("%sPopup%d", addon.name, count)
		popup = self:Bind(CreateFrame("CheckButton", name, UIParent, "SecureHandlerShowHideTemplate,SecureHandlerDragTemplate,SecureHandlerEnterLeaveTemplate,SecureActionButtonTemplate,ActionButtonTemplate"))
		popup:Initialize()
		popup.rid = count

		popup:SetAttribute("_onshow", [[ -- self
			control:CallMethod("OnShow")
		]])
		popup:SetAttribute("_onhide", [[ -- self
			control:CallMethod("OnHide")
		]])
		popup:SetAttribute("_onenter", [[ -- self
			self:GetParent():SetAttribute("state-hover", true)
			control:CallMethod("OnEnter")
		]])
		popup:SetAttribute("_onleave", [[ -- self
			control:CallMethod("OnLeave")
		]])
		popup:SetAttribute("_ondragstart", [[ -- self, button, kind, value, ...
			--control:CallMethod("OnDragStart")
			print(self:GetName(), "_ondragstart", button, kind, value, ...)
		]])
		popup:SetAttribute("_onreceivedrag", [[ -- self, button, kind, value, ...
			--control:CallMethod("OnReceiveDrag")
			print(self:GetName(), "_onreceivedrag", button, kind, value, ...)
			self:SetAttribute("type", kind)
			self:SetAttribute(kind, value)
			control:CallMethod("Update")
		]])
		popup:WrapScript(popup, "OnClick", [[ -- self, button, down, ...
			control:CallMethod("OnClick", button, down)

			local click = buttons[button]
			if click == 1 or click == 3 then
				self:GetParent():SetAttribute("state-active", tostring(self:GetID()))
			end
			self:GetParent():SetAttribute("state-hover", false)
			if click == 3 then
				return false
			end
		]])
	end
	used[popup] = true

	return popup
end

function addon:IteratePopup()
	return pairs(used)
end

function prototype:Store()
	used[self] = nil

	self:Reset()

	cache[self] = true
end